package com.china08.yxyapi.api.manage.tec.teaching.live.lessonManage;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.util.Assert;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.live.YxyLiveLesson;
import com.china08.yxyapi.entity.db.live.YxyLiveLessonItem;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.repository.db.live.YxyLiveLessonItemRepository;
import com.china08.yxyapi.repository.db.live.YxyLiveLessonRepository;
import com.china08.yxyapi.security.profile.YxyProfile;

import io.swagger.annotations.ApiOperation;

/**
 * 我的教学-直播课-教师-直播课更新
 * @author 赵亚辉
 *
 */
@CrossOrigin
@RestController
public class LiveManageLessonUpdateController extends YxyApiBaseController{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private RestTemplate restTemplate;
	@Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;
	@Autowired
	private YxyLiveLessonRepository liveLessonRepository;
	@Autowired
	private YxyLiveLessonItemRepository liveLessonItemRepository;
	
	private SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@ApiOperation(value = "直播课编辑")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/live/liveManageLesson/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
	public RespModel add(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) throws ParseException {
		
		RespModel respModel=new RespModel();
		Integer status=200;
		try {
			YxyProfile profile = getProfile(request, response);
			String schoolId = profile.getSchoolId();
			String catalogId1 = reqModel.catalogId1;
			String catalogId2 = reqModel.catalogId2;
			String catalogId3 = reqModel.catalogId3;
			String id = reqModel.id;
			Integer scope = reqModel.scope;
			String eduOfficeId = reqModel.eduOfficeId;
			String summary = reqModel.summary;
			String cover = reqModel.cover;
			List<RespLessonItem> lessonItemList = reqModel.lessonItemList;
			Integer count = lessonItemList.size();
			Integer liveType = reqModel.liveType;

			YxyLiveLesson lesson = liveLessonRepository.findById(id);
			lesson.setScope(scope);
			if (scope == 1) {
				lesson.setCatalogSchoolId(schoolId);
			} else {
				lesson.setCatalogSchoolId(eduOfficeId);
			}
			if (StringUtils.isNotEmpty(catalogId1)) {
				lesson.setCatalogId1(catalogId1);
			}
			if (StringUtils.isNotEmpty(catalogId2)) {
				lesson.setCatalogId2(catalogId2);
			}
			if (StringUtils.isNotEmpty(catalogId3)) {
				lesson.setCatalogId3(catalogId3);
			}
			lesson.setLiveType(reqModel.liveType);
			lesson.setName(reqModel.name);
			if (StringUtils.isNotEmpty(summary)) {
				lesson.setSummary(summary);
			}
			if (StringUtils.isNotEmpty(cover)) {
				lesson.setCover(cover);
			}
			lesson.setCount(count);
			lesson.setLiveType(liveType);
			liveLessonRepository.save(lesson);
			String lessonId = lesson.getId();

			//删除之前的课时
			//delLessonItemByLessonId(lessonId);

			for (RespLessonItem item : lessonItemList) {
				String lessonItemId=item.dateLessonItem;
				String dateLessonItem = item.dateLessonItem;
				String timeStartLessonItem = item.timeStartLessonItem;
				String timeEndLessonItem = item.timeEndLessonItem;
				Integer duration = item.duration;
				Date beginDate = sf.parse(dateLessonItem + " " + timeStartLessonItem + ":00");
				Date endDate = sf.parse(dateLessonItem + " " + timeEndLessonItem + ":00");
				
				YxyLiveLessonItem lessonItem = null;
				if(StringUtils.isNotEmpty(lessonItemId)){
					lessonItem=liveLessonItemRepository.findById(lessonItemId);
				}else{
					lessonItem = new YxyLiveLessonItem();
				}
				lessonItem.setLessonId(lessonId);
				lessonItem.setBeginDate(beginDate);
				lessonItem.setEndDate(endDate);
				lessonItem.setDuration(duration);
				lessonItem.setStatus(0);
				if (liveType == 0) {
					lessonItem.setRecordOpen(1);
				}
				liveLessonItemRepository.save(lessonItem);
			}
		} catch (Exception e) {
			status=500;
		}
		respModel.status=status;
		
		return respModel;
	}
	
	public void delLessonItemByLessonId(String lessonId){
		
		String dataSQL="delete from yxy_live.yxy_live_lesson_item where lesson_id='"+lessonId+"'";
		jdbcTemplate.execute(dataSQL);
	}
	
	public String findPhoneByUserId(String userId){
		String mobile="";
		
		ReqMobileModel reqMobileModel=new ReqMobileModel();
		reqMobileModel.userId = userId;
		String url=yxyApiYxUrl+"/comm/user/getMobile/id";
		
		HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
        Map<String, Object> formMap = new HashMap<String, Object>();
        formMap.put("userId", userId);
        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
        RespMobileModel respMobileModel = restTemplate.postForObject(url,formEntity, RespMobileModel.class);
		if(respMobileModel!=null) {
			mobile=respMobileModel.mobile;
		}
		
		return mobile;
	}
	
	protected static class ReqMobileModel {

        // 用户id
        public String userId;
    }
	
	protected static class RespMobileModel{

        public String userNick;

        public String mobile;

    }
	
	protected static class ReqModel extends YxyApiReqModel{
		
		public String id;
		
		public String name;
		
		public String summary;
		
		public String cover;
		
		public Integer scope;
		
		public String eduOfficeId;
		
		public Integer liveType;
		
		public String catalogId1;
		
		public String catalogId2;
		
		public String catalogId3;
		
		public List<RespLessonItem> lessonItemList;
		
		@Override
        public void autoCheck() {
           
			Assert.notNull(StringUtils.defaultIfBlank(id, null), "请填写课程id");
            Assert.notNull(StringUtils.defaultIfBlank(name, null), "请填写课程名称");
            Assert.notNull(scope==null, "请填写开设范围");
            if (scope==1){
            	Assert.notNull(StringUtils.defaultIfBlank(eduOfficeId, null), "请填写教育局id");
            }
            Assert.notNull(liveType==null, "请填写直播设置");
            Assert.notNull(StringUtils.defaultIfBlank(catalogId1, null), "请填写目录id");
            Assert.notNull(lessonItemList==null||lessonItemList.size()==0, "请填写课时");
        }
	}
	
	protected static class RespLessonItem {
		
		private String lessonItemId;
		
		public String dateLessonItem;
		
		public String timeStartLessonItem;
		
		public String timeEndLessonItem;
		
		public Integer duration;
	}
	
	protected static class RespModel {
		
		public Integer status;
		
	}
	
	

}
